package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

// 菜品模块
@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {

    //菜品表
    @Autowired
    private DishMapper dishMapper;

    //分类表
    @Autowired
    private CategoryMapper categoryMapper;

    //口味表
    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    //分页和模糊查询
    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {

        //模糊查询
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(name),Dish::getName,name);

        //分页查询
        //开启分页
        Page<Dish> page = new Page<>(pageNum, pageSize);
        //调用DishMapper查询
        page = dishMapper.selectPage(page, qw);
        //遍历菜品
        List<Dish> dishList = page.getRecords();
        for (Dish dish : dishList) {
            //根据菜品id查询口味表
            LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
            dqw.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(dqw);
            //封装口味列表
            dish.setFlavors(dishFlavorList);
            //根据分类ID查询分类信息
            Category category = categoryMapper.selectById(dish.getCategoryId());
            //分装分类名称
            dish.setCategoryName(category.getName());
        }
        //返回分页对象
        return page;
    }

    // 新增菜品
    @Override
    public void save(Dish dish) {
        // 1.新增菜品基本信息
        log.info("新增之前：" + dish.getId());
        dishMapper.insert(dish);
        log.info("新增之后：" + dish.getId()); // 主键返回

        // 2.遍历口味
        for (DishFlavor flavor : dish.getFlavors()) {
            // 关联菜品id
            flavor.setDishId(dish.getId());
            // 新增口味
            dishFlavorMapper.insert(flavor);
        }

        //为保障缓存一致性
        //删除当前缓存
        redisTemplate.delete("dish:" + dish.getCategoryId());
    }

    // 回显菜品
    @Override
    public Dish findById(Long id) {
        // 1.先查菜品
        Dish dish = dishMapper.selectById(id);
        // 2.根据菜品id查询口味
        // 2-1 构建条件
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        // 2-2  调用mapper
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(qw);
        // 3.将口味设置到菜品
        dish.setFlavors(dishFlavorList);
        //  4.返回菜品
        return dish;
    }

    // 修改菜品
    @Override
    public void updateById(Dish dish) {
        // 1.修改菜品基本信息
        dishMapper.updateById(dish);
        // 2.根据菜品id删除原来口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(qw);
        // 3.遍历新增口味
        for (DishFlavor flavor : dish.getFlavors()) {
            // 关联菜品id
            flavor.setDishId(dish.getId());
            // 口味新增
            dishFlavorMapper.insert(flavor);
        }


        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);
    }

    //批量删除
    @Override
    public ResultInfo deleteBatchIds(List<Long> ids) {
        /*//遍历id
        for (Long id : ids) {

            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus()==1){
                throw new CustomException("在售菜品,无法删除!!!");
                //return ResultInfo.error("在售菜品,无法删除!!!");
            }
            // 先删菜品
            dishMapper.deleteById(id);

            // 再删口味
            LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
            dqw.eq(DishFlavor::getDishId, id);
            dishFlavorMapper.delete(dqw);
        }
        return ResultInfo.success();*/

       /* //方法2
        //根据ids直接查询dish集合
        List<Dish> dishList = dishMapper.selectBatchIds(ids);
        //遍历
        for (Dish dish : dishList) {
            //判断是否有启售的 ,若有无法删除
            if (dish.getStatus() ==1) {
                throw new CustomException("在售菜品,无法删除!!!");
            }
        }
        //若没有 执行删除
        dishMapper.deleteBatchIds(ids);
        //根据dish_id 删除菜品口味
        dishFlavorMapper.delete(new LambdaQueryWrapper<DishFlavor>().in(DishFlavor::getDishId,ids));
        return ResultInfo.success();
        */

       //方法3
        //创建条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //设置条件
        wrapper.in(Dish::getId,ids)
               .eq(Dish::getStatus, 1);
        //调用mapper条件查询个数
        if (dishMapper.selectCount(wrapper)>0) {
            throw new CustomException("在售菜品,无法删除!!!");
        }
        //若没有 执行删除
        dishMapper.deleteBatchIds(ids);
        //根据dish_id 删除菜品口味
        dishFlavorMapper.delete(new LambdaQueryWrapper<DishFlavor>().in(DishFlavor::getDishId,ids));

        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);
        return ResultInfo.success();


    }

    //停售/启售
    @Override
    public void updateStatus(Integer status, List<Long> ids) {
        // 条件对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        // 修改实体
        Dish dish = new Dish();
        dish.setStatus(status);
        // 调用mapper
        dishMapper.update(dish, wrapper);

        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);

    }

    // 根据分类查询菜品列表
    @Override
    public List<Dish> findListByCategoryId(long categoryId) {

        // 1.构建条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //根据分类ID查询菜品
        wrapper.eq(Dish::getCategoryId,categoryId);
        // 起售状态
        wrapper.eq(Dish::getStatus, 1);
        //查询
        return dishMapper.selectList(wrapper);
    }

    //套餐添加菜品检索
    @Override
    public List<Dish> findListByName(String name) {

        // 1.构建条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //模糊查询
        wrapper.like(Dish::getName,name);
        // 起售状态
        wrapper.eq(Dish::getStatus, 1);

        List<Dish> dishList = dishMapper.selectList(wrapper);
        //查询
        return dishList;
    }


    // 菜品展示
    @Override
    public List<Dish> findList(Long categoryId, Integer status) {
        //声明返回list
        List<Dish> dishList= null;

        // 定义菜品分类的key
        String dishKey = "dish:" + categoryId;

        //判断缓存
        if (redisTemplate.hasKey(dishKey)) {
            log.info("查询Redis");
            //如果有返回
             dishList =(List<Dish>)redisTemplate.opsForValue().get(dishKey);
        }else {
            log.info("查询MySql");

            // 1.查询该分类下起售的菜品有哪些
            // 1-1构建条件
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(Dish::getCategoryId, categoryId);
            qw.eq(Dish::getStatus, status);
            // 1-2mapper查询
             dishList = dishMapper.selectList(qw);
            // 2.遍历菜品列表
            for (Dish dish : dishList) {
                // 根据菜品id查询口味
                List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, dish.getId()));
                // 添加到菜品中
                dish.setFlavors(dishFlavorList);
            }

            // 同步到redis
            redisTemplate.opsForValue().set(dishKey, dishList);
        }
        // 3.返回结果
        return dishList;
    }
}
